# -*- coding: utf-8 -*-
import hashlib
import hmac
import json
import random
import string
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.channel.pay import check_channel_order
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '22': {  # test
        'API_KEY': '35de170fc7836ea645e1a7d7b307ff6e',
    },
    '77': {
        'API_KEY': 'hTuDu8mArbhpPMSEAAIqJ22LltMp6sEY',
    },
    'gateway': 'http://api.qkkpay.com/hspay/api_node/',
    'query_gateway': 'http://api.qkkpay.com/replacepay/queryorder',
}


# weixin	微信扫码支付
# alipay	支付宝扫码支付
# alipaywap	支付宝WAP支付
# wxwap	微信wap支付
# weixincode	微信付款码支付
# alipaycode	支付宝付款码支付


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway():
    return APP_CONF['gateway']


def _get_query_gateway():
    return APP_CONF['query_gateway']


def hmac_md5(parameter, key):
    return hmac.new(key, parameter, hashlib.md5).hexdigest()


def generate_verify_sign(parameter, key):
    s = ''
    for k in sorted(parameter.iterkeys()):
        s += '%s=%s&' % (k, parameter[k])
    _LOGGER.info('qiantongyunpay response sign params:%s' % s)
    return hmac_md5(s[:len(s) - 1], key)


def verify_notify_sign(params, key):
    sign = params['hmac']
    params.pop('hmac')
    params.pop('rb_BankId')
    params.pop('ro_BankOrderId')
    params.pop('rp_PayDate')
    params.pop('rq_CardNo')
    params.pop('ru_Trxtime')
    calculated_sign = generate_verify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("qiantongyunpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('p0_Cmd', 'Buy'),
        ('p1_MerId', app_id),
        ('p2_Order', str(pay.id)),
        ('p3_Amt', ('%.2f' % pay_amount)),
        ('p4_Cur', 'CNY'),
        ('p5_Pid', 'none'),
        ('p6_Pcat', 'none'),
        ('p7_Pdesc', 'none'),
        ('p8_Url', '{}/pay/api/{}/qiantongyunpay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('pa_MP', 'none'),
        ('pd_FrpId', service),
        ('pr_NeedResponse', '1'),
    ))
    parameter_dict['hmac'] = generate_verify_sign(parameter_dict, api_key)
    _LOGGER.info("qiantongyunpay create date: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['p2_Order'])
    if service not in ('weixin', 'bdpay', 'alipay'):
        html_text = _build_form(parameter_dict, _get_gateway())
        cache_id = redis_cache.save_html(pay.id, html_text)
        url = settings.PAY_CACHE_URL + cache_id
        _LOGGER.info('yangyangpay url: %s', url)
        return {'charge_info': url}
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(), data=parameter_dict, headers=headers, timeout=5)
    if response.text.strip().startswith('<html>') or response.text == '':
        cache_id = redis_cache.save_html(pay.id, response.text)
        _LOGGER.info("qiantongyunpay response url: %s", settings.PAY_CACHE_URL + cache_id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    resp_obj = json.loads(response.text)
    if str(resp_obj['status']) != '0':
        return {'charge_info': resp_obj['Msg']}
    pay_name_dict = {'alipay': '支付宝', 'weixin': '微信', 'bdpay': '银联', 'jdpay': '京东', 'qqmobile': 'QQ'}
    pay_name = pay_name_dict.get(service, '')
    pay_money = parameter_dict['p3_Amt']
    pay_order = parameter_dict['p2_Order']
    url = resp_obj['payImg']
    template_data = {'url': url, 'pay_name': pay_name, 'pay_money': pay_money, 'pay_order': pay_order}
    t = get_template('qrcode_quma.html')
    html = t.render(Context(template_data))
    cache_id = redis_cache.save_html(pay.id, html)
    _LOGGER.info('qiantongyunpay response data: %s', resp_obj)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success异步回调
def check_notify_sign(request, app_id):
    _LOGGER.info("qiantongyunpay notify body: %s", request.body)
    if request.method == 'GET':
        data = dict(request.GET.iteritems())
    else:
        data = dict(request.POST.iteritems())
    _LOGGER.info("qiantongyunpay notify data: %s, order_id is: %s", data, data['r6_Order'])
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['r6_Order']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('qiantongyunpay event does not contain valid pay ID')
    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['r1_Code'])
    trade_no = data['r6_Order']
    total_fee = float(data['r3_Amt'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '1':
        _LOGGER.info('qiantongyunpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    rand_num = ''.join(random.sample(string.ascii_letters + string.digits, 32))
    parameter_dict = OrderedDict((
        ('p1_MerId', app_id),
        ('p2_Order', str(pay_id)),
        ('nonce', rand_num),
    ))
    parameter_dict['sign'] = generate_verify_sign(parameter_dict, api_key)
    _LOGGER.info('qiantongyunpay query data %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['p2_Order'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('qiantongyunpay query rsp, %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_msg = data['Msg']
        trade_status = data['respCode']
        trade_no = str(data['p2_Order'])
        total_fee = float(data['p3_Amt'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee,
        }
        if trade_status == '00':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('qiantongyunpay query order success, msg:%s ' % trade_msg)
            order_db.add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
        else:
            _LOGGER.info(
                'qiantongyunpay query order status: %s,  msg:%s' % (trade_status, trade_msg))
    else:
        _LOGGER.warn('qiantongyunpay data error, status_code: %s', response.status_code)
